package com.unionpay.upyzt.example;

import com.unionpay.upyzt.exception.UpyztException;
import com.unionpay.upyzt.model.Refund;
import com.unionpay.upyzt.resp.RefundResp;

import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;

public class RefundExample {

    public RefundExample(String tradeId) {
        this.tradeId = tradeId;
    }

    protected String tradeId;

    /**
     * 运行 Demos
     *
     * @param tradeId 交易ID
     */
    public static String runDemos(String tradeId) throws UpyztException {
        RefundExample refundExample = new RefundExample(tradeId);

        // 退款
        RefundResp refundResp = refundExample.create();

        // 退款订单查询（系统订单号）
        refundResp = refundExample.retrieveById(refundResp.getRefundId());

        // 退款订单查询（平台订单号）
        refundResp = refundExample.retrieveByOutOrderNo(refundResp.getOutOrderNo());

        return refundResp.getRefundId();
    }

    /**
     * 退款
     *
     * @return 返回参数
     * @throws UpyztException 异常
     */
    public RefundResp create() throws UpyztException {
        Map<String, Object> params = new HashMap<>();
        params.put("out_order_no", Main.generateRandomOutNo());
        params.put("sent_at", OffsetDateTime.now().toString());
        params.put("amount", 100);
        params.put("orig_trade_id", this.tradeId);
        params.put("remark", "用于 SDK 示例测试");
        // params.put("total_amount", 101);
        // params.put("discount_amount", 1);

        System.out.println("------- 退款 -------");
        RefundResp resp = Refund.create(params);
        System.out.println(resp);
        return resp;
    }

    /**
     * 退款订单查询（系统订单号）
     *
     * @return 返回参数
     * @throws UpyztException 异常
     */
    public RefundResp retrieveById(String id) throws UpyztException {
        System.out.println("------- 退款订单查询（系统订单号） -------");
        RefundResp resp = Refund.retrieveById(id);
        System.out.println(resp);
        return resp;
    }

    /**
     * 退款订单查询（平台订单号）
     *
     * @return 返回参数
     * @throws UpyztException 异常
     */
    public RefundResp retrieveByOutOrderNo(String outOrderNo) throws UpyztException {
        System.out.println("------- 退款订单查询（平台订单号） -------");
        RefundResp resp = Refund.retrieveByOutOrderNo(outOrderNo);
        System.out.println(resp);
        return resp;
    }

}
